package com.atguigu.gmall.order.listener;

import com.atguigu.gmall.order.service.OrderInfoService;
import com.atguigu.gmall.rabbit.service.RabbitService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class WareStockListener {

    @Autowired
    private OrderInfoService orderInfoService ;

    @Autowired
    private RabbitService rabbitService ;

    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(value = "queue.ware.order" , durable = "true") ,
                    exchange = @Exchange(value = "exchange.direct.ware.order" , type = ExchangeTypes.DIRECT) ,
                    key = { "ware.order" }
            )
    })
    public void wareStockListener(Message message , Channel channel) {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        byte[] body = message.getBody();
        String wareStockJSON = new String(body) ;
        try {
            orderInfoService.wareStockUpateStatus(wareStockJSON) ;
            channel.basicAck(deliveryTag , true);
        } catch (IOException e) {
            e.printStackTrace();
            rabbitService.retry(channel , deliveryTag , wareStockJSON , 5);
        }
    }

}
